<template>
  <el-form ref="form" :label-width="lw" :model="value">
    <el-form-item
      :prop="key"
      :rules="item.rules"
      :label="item.title"
      v-for="(item, key) in options"
      :key="key"
    >
      <el-input
        v-model="value[key]"
        :typle="item.type"
        :maxlength="item.max"
        :disabled="item.dis"
        :placeholder="item.ph"
        v-if="item.tag === 'input'"
      ></el-input>
      <el-upload
        v-else-if="item.tag === 'upload'"
        :action="item.url"
        :file-list="value[key]"
        :headers="item.headeres"
        :on-success="(res, file, fileList) => fileUpload(key, fileList)"
        list-type="picture"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
    </el-form-item>
  </el-form>
</template>
<script>
import { deepClone } from "uti/common.js";
/**
 * 是否为数字
 */
const isNumber = (value) => typeof value === "number";
export default {
  name: "MyForm",
  methods: {
    /**
     * 文件上传成功的回调
     */
    fileUpload(key, fileList) {
      this.$emit("input", { ...this.value, [key]: fileList });
    },
    /***
     * 验证
     */
    validate() {
      return this.$refs.form.validate();
    },
    /**
     * 清空验证规则
     */
    clear() {
      this.$refs.form.clearValidate;
    },
  },
  props: {
    /***
     * label的宽度
     */
    lw: {
      type: String,
      default: "70px",
    },
    /***
     * 绑定数据的实体
     */
    value: {
      type: Object,
      default: () => {},
    },
    /**
     * 表单配置项
     */
    opts: {
      type: Object,
      required: true,
      default: () => {},
    },
  },

  computed: {
    /**
     * 配置项
     */
    options() {
      const _opts = deepClone(this.opts);
      for (const key in _opts) {
        const item = _opts[key];
        item.tag = item.tag || "input";
        item.type = item.type || "text";
        item.rules = item.rules || [];

        if (item.required) {
          item.rules.unshift({ required: true });
        }

        for (const rule of item.rules) {
          if (rule.message) {
            continue;
          }
          if (rule.required) {
            rule.message = item.title + "不能为空";
          } else if (isNumber(rule.min) && isNumber(rule.max)) {
            rule.message = `${item.title}长度为${rule.min}到${rule.max}位`;
          } else if (isNumber(rule.min)) {
            rule.message = `${item.title}最小长度为${rule.min}位`;
          } else if (isNumber(rule.max)) {
            rule.message = `${item.title}最大长度为${rule.max}位`;
          }
        }
      }
      return _opts;
    },
  },
};
</script>